using Microsoft.SqlServer.Management.Sdk.Sfc;
using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Runtime.CompilerServices;

namespace Microsoft.SqlServer.Management.SqlManagerUI.Scripting
{
	internal class ScriptedObjectCollection : KeyedCollection<string, ScriptContainer>
	{
		private GetKeyHandler keyHandler;

		[CompilerGenerated]
        //private static GetKeyHandler <>9__CachedAnonymousMethodDelegate1;

		public ScriptedObjectCollection() : this((Urn source) => source)
		{
		}

		public ScriptedObjectCollection(GetKeyHandler keyHandler)
		{
			if (keyHandler == null)
			{
				throw new ArgumentNullException("keyHandler");
			}
			this.keyHandler = keyHandler;
		}

		public void ScriptAll(ScriptWriter scriptWriter)
		{
			foreach (ScriptContainer current in this)
			{
				current.Script(scriptWriter);
			}
		}

		public void AddItem(Urn source)
		{
			this.GetScriptContainerForItem(new Microsoft.SqlServer.Management.SqlManagerUI.ObjectInfo("", source));
		}

		public void AddScriptFragment(Microsoft.SqlServer.Management.SqlManagerUI.ObjectInfo objectInfo, IEnumerable script, ScriptActions action)
		{
			ScriptContainer scriptContainerForItem = this.GetScriptContainerForItem(objectInfo);
			scriptContainerForItem.AddFragment(objectInfo, script, action);
		}

		protected override string GetKeyForItem(ScriptContainer item)
		{
			return item.Key;
		}

		private ScriptContainer GetScriptContainerForItem(Microsoft.SqlServer.Management.SqlManagerUI.ObjectInfo objectInfo)
		{
			Urn urn = this.keyHandler(objectInfo.Urn);
			ScriptContainer scriptContainer;
			if (base.Contains(urn))
			{
				scriptContainer = base[urn];
				scriptContainer.ObjectInfo.Name = objectInfo.Name;
				scriptContainer.ObjectInfo.Schema = objectInfo.Schema;
			}
			else
			{
				scriptContainer = ScriptedObjectCollection.GetNewScriptContainer(objectInfo);
				base.Add(scriptContainer);
			}
			return scriptContainer;
		}

		private static ScriptContainer GetNewScriptContainer(Microsoft.SqlServer.Management.SqlManagerUI.ObjectInfo objectInfo)
		{
			if (objectInfo.Urn.Type == "Table")
			{
				return new ScriptTableContainer(objectInfo);
			}
			return new ScriptObjectContainer(objectInfo);
		}
	}
}
